import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Button, message, Modal } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import FooterToolbar from '@/components/FooterToolbar';
import Customer from '../../components/SendOrderCustomer';
import Area from '../../components/Area';
import styles from '../../../utils/utils.less';

const FormItem = Form.Item;

@connect(({ addempsend, loading }) => ({
  addempsend,
  loading: loading.models.addempsend,
  agreePageData: addempsend.agreePageData,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      sleectedList: [],
      selectedRowKeys: [],
    };
  }

  componentDidMount() {
    this.getList(1, 10);
  }

  // 获取列表
  getList = (currentPage = 1, pageSizes = 10) => {
    const { dispatch, form } = this.props;
    const pageArg = { currentPage, pageSize: pageSizes };
    form.validateFields((err, value) => {
      dispatch({
        type: 'addempsend/getAssoDetail',
        payload: {
          pageArg,
          ...value,
        },
      });
    });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addempsend/tableChange',
      payload: {},
    });
    this.getList(pagination.current, pagination.pageSize);
  };

  // 解绑
  untying = record => {
    const {
      dispatch,
      agreePageData: {
        pagination: { current, pageSize, total },
      },
    } = this.props;
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      title: '解绑之后再有相同业务情况需要重新关联，且无法自动发单，是否确认解绑？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'addempsend/untyData',
          payload: { sendOrdSuppProtId: record.sendOrdSuppProtId },
        }).then(response => {
          if (response.success) {
            message.success('解绑成功!');
            const selectedLen = 1;
            if (
              current > 1 &&
              (total % pageSize === Number(selectedLen) || Number(pageSize) === Number(selectedLen))
            ) {
              this.getList(current - 1, pageSize);
            } else {
              this.getList(current, pageSize);
            }
          } else {
            message.warning(response.message || '解绑失败!');
          }
        });
      },
    });
  };

  getData = (value, id) => {
    const { form } = this.props;
    if (id) {
      form.setFieldsValue({ [id]: value });
      this.setState({ [id]: value });
    }
  };

  render() {
    const { sleectedList, selectedRowKeys } = this.state;
    const { agreePageData } = this.props;
    const columns = [
      {
        title: '客户名称',
        width: 180,
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: text => text || '--',
      },
      {
        title: '执行地',
        width: 180,
        dataIndex: 'cityName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: text => text || '--',
      },
      {
        title: '服务产品',
        width: 180,
        dataIndex: 'pdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: text => text || '--',
      },

      {
        title: '供应商',
        width: 180,
        dataIndex: 'recvSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: text => text || '--',
      },

      {
        title: '供应商协议',
        width: 180,
        dataIndex: 'suppProtName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: text => text || '--',
      },

      {
        title: '操作',
        width: 100,
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <a style={{ margin: '0 8px 0 0' }} onClick={() => this.untying(record)}>
            解绑
          </a>
        ),
      },
    ];

    const {
      form: { getFieldDecorator },
      loading,
    } = this.props;
    const tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>
            <Form>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                  <FormItem label="客户名称" {...tableSearchLayout}>
                    {getFieldDecorator('custId', {})(
                      <Customer getData={this.getData} allowClear />
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem {...tableSearchLayout} label="执行地区">
                    {getFieldDecorator('cityId', {})(<Area allowClear style={{ width: '100%' }} />)}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <Button type="primary" onClick={() => this.getList()}>
                    查询
                  </Button>
                </Col>
              </Row>
            </Form>
          </div>
        </Card>
        <Card style={{ border: '0px', marginBottom: 24, fontSize: 16, color: '#262626' }}>
          <StandardTable
            style={{ width: '100%' }}
            selectedRows={sleectedList}
            selectedRowKeys={selectedRowKeys}
            loading={loading}
            data={agreePageData}
            rowKey={(record, index) => index}
            columns={columns}
            onSelectRow={false}
            rowSelection={false}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <FooterToolbar style={{ width: '100%' }}>
          <Button style={{ marginRight: 10 }} onClick={() => router.goBack()}>
            返回
          </Button>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
